package com.gxa.javaserver.socket;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 服务端的线程
 * @author:Teacher黄
 * @date:Created at 2020/06/16
 */
public class ServerThread extends Thread {


    /**
     * socket连接对象
     */
    private Socket socket;

    /**
     * 输入流
     */
    private DataInputStream dataInputStream;

    /**
     * 输出流
     */
    private DataOutputStream dataOutputStream;


    /**
     * 构造器
     * @param socket
     */
    public ServerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            // 获取客户端信息
            InetAddress inetAddress = socket.getInetAddress();
            // ip
            String ipAddress = inetAddress.getHostAddress();
            System.out.println("客户端:"+ipAddress+",连接成功!");
            // 准备输入输出流
            dataInputStream = new DataInputStream(socket.getInputStream());
            dataOutputStream = new DataOutputStream(socket.getOutputStream());
            // 接收客户端的消息
            String msg = dataInputStream.readUTF();
            System.out.println("客户端:"+ipAddress+":"+msg);
            // 发送消息
            dataOutputStream.writeUTF("我是唐伯虎!!!!!");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            closeResources(dataInputStream, dataOutputStream, socket);
        }

    }


    /**
     * 关闭资源的方法
     * @param dataInputStream
     * @param dataOutputStream
     * @param socket
     */
    private void closeResources(DataInputStream dataInputStream, DataOutputStream dataOutputStream, Socket socket){
        try {
            if(dataInputStream != null){
                dataInputStream.close();
            }
            if (dataOutputStream != null) {
                dataOutputStream.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
